#region Copyright Jonathan Quiros

//	
// All rights are reserved. Reproduction or transmission in whole or in 
// part, in any form or by any means, electronic, mechanical or otherwise, 
// is prohibited without the prior written consent of the copyright owner.
//
// Filename: UserFormModelBinder.cs
//

#endregion

using System.Text.RegularExpressions;
using System.Web.Mvc;
using Novagoal.Website.Models.Forms;

namespace Novagoal.Website.WebApp.ModelBinders
{
    public class UserFormModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = base.BindModel(controllerContext, bindingContext);
            var formModel = model as UserFormModel;

            if (formModel != null)
            {
                if (!IsValidEmail(formModel.EmailAddress))
                {
                    bindingContext.ModelState.AddModelError("EmailAddress", "Email address is invalid");
                }
            }

            return model;
        }

        private bool IsValidEmail(string strIn)
        {
            if (string.IsNullOrEmpty(strIn))
                return false;

            // Return true if strIn is in valid e-mail format.
            return Regex.IsMatch(strIn,
                   @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                   @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                   RegexOptions.IgnoreCase);
        }
    }
}